import GoEasy from "goeasy-lite";

// 内部状态
let goeasyInstance = null;
let pubsub = null;
let connected = false;

/**
 * 初始化 GoEasy
 */
export async function initGoEasy(appkey, host = "hangzhou.goeasy.io") {
    if (goeasyInstance) return;

    const options = {
        host,
        appkey,
        modules: ["pubsub"],
    };

    goeasyInstance = await GoEasy.getInstance(options);
    pubsub = goeasyInstance.pubsub;
}

/**
 * 建立连接
 */
export function connectGoEasy(userId, userData) {
    if (!goeasyInstance) throw new Error("请先调用 initGoEasy() 初始化");

    goeasyInstance.connect({
        id: userId,
        data: userData || {},
        onSuccess: function () {
            console.log("GoEasy 连接成功");
            connected = true;
        },
        onFailed: function (error) {
            console.error(
                "GoEasy 连接失败, code: " + error.code + ", msg: " + error.content
            );
            connected = false;
        },
        onProgress: function (attempts) {
            console.log("GoEasy 正在连接...", attempts);
        },
    });
}

/**
 * 订阅频道
 */
export function subscribeChannel(channel, callback) {
    if (!pubsub) throw new Error("请先调用 initGoEasy() 初始化");
    console.log(channel, "通道ID");
    pubsub.subscribe({
        channel: channel,
        onMessage: function (msg) {
            console.log("收到消息:", msg);
            callback(msg);
        },
        onSuccess: function () {
            console.log("频道 " + channel + " 订阅成功");
            console.log(channel, "通道ID");
        },
        onFailed: function (error) {
            console.error(
                "频道 " + channel + " 订阅失败, code: " + error.code + ", msg: " + error.content
            );
        },
    });
}

/**
 * 取消订阅频道
 */
export function unsubscribeChannel(channel) {
    if (!pubsub) return;

    pubsub.unsubscribe({
        channel: channel,
        onSuccess: function () {
            console.log("频道 " + channel + " 已取消订阅");
        },
        onFailed: function (error) {
            console.error(
                "取消订阅失败, code: " + error.code + ", msg: " + error.content
            );
        },
    });
}

/**
 * 发布消息
 */
export function publishMessage(channel, message) {
    if (!pubsub) throw new Error("请先调用 initGoEasy() 初始化");
    pubsub.publish({
        channel: channel,
        message: message,
        qos: 1,
        onSuccess: function () {
            console.log("消息发布成功");
        },
        onFailed: function (error) {
            console.error("消息发送失败, code: " + error.code + ", msg: " + error.content);
        },
    });
}

/**
 * 断开连接
 */
export function disconnectGoEasy() {
    if (!goeasyInstance) return;
    goeasyInstance.disconnect();
    connected = false;
    console.log("GoEasy 已断开连接");
}

/**
 * 获取连接状态
 */
export function isConnected() {
    return connected;
}
